package com.irdstudio.rsp.rule.service.impl;

import com.irdstudio.rsp.drools.exception.FireRuleErrorEnum;
import com.irdstudio.rsp.drools.exception.FireRuleException;
import com.irdstudio.rsp.rule.common.BizUtil;
import com.irdstudio.rsp.rule.common.constant.Constant.RULE_COLL_STATE;
import com.irdstudio.rsp.rule.common.constant.Constant.RULE_COLL_TYPE;
import com.irdstudio.rsp.rule.common.constant.Constant.YES_OR_NO;
import com.irdstudio.rsp.rule.dao.BizRuleAdapterDao;
import com.irdstudio.rsp.rule.dao.SRuleCollDetailDao;
import com.irdstudio.rsp.rule.dao.SRuleCollInfoDao;
import com.irdstudio.rsp.rule.dao.SRuleCollParamDao;
import com.irdstudio.rsp.rule.dao.domain.BizRuleAdapter;
import com.irdstudio.rsp.rule.dao.domain.SRuleCollDetail;
import com.irdstudio.rsp.rule.dao.domain.SRuleCollInfo;
import com.irdstudio.rsp.rule.dao.domain.SRuleCollParam;
import com.irdstudio.rsp.rule.service.facade.SRuleCollInfoService;
import com.irdstudio.rsp.rule.service.vo.BizRuleAdapterVO;
import com.irdstudio.rsp.rule.service.vo.SRuleCollDetailVO;
import com.irdstudio.rsp.rule.service.vo.SRuleCollInfoVO;
import com.irdstudio.rsp.rule.service.vo.SRuleCollParamVO;
import com.irdstudio.sdk.beans.core.base.FrameworkService;
import com.irdstudio.sdk.ssm.vo.UserInfo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
 * <p>ServiceImpl: 规则集信息				<p>
 * @author AutoCoder
 * @date 2019-10-30
 */
@Service("sRuleCollInfoServiceImpl")
public class SRuleCollInfoServiceImpl implements SRuleCollInfoService, FrameworkService {
	
	private static Logger logger = LoggerFactory.getLogger(SRuleCollInfoServiceImpl.class);

	@Autowired
	private SRuleCollInfoDao sRuleCollInfoDao;

	@Autowired
    private SRuleCollDetailDao sRuleCollDetailDao;

	@Autowired
    private SRuleCollParamDao sRuleCollParamDao;

	@Autowired
	private BizRuleAdapterDao bizRuleAdapterDao;
	
	/**
	 * 新增操作
	 */
	public int insertSRuleCollInfo(SRuleCollInfoVO inSRuleCollInfoVo) {
		logger.debug("当前新增数据为:"+ inSRuleCollInfoVo.toString());
		int num = 0;
		try {
			SRuleCollInfo sRuleCollInfo = new SRuleCollInfo();
			beanCopy(inSRuleCollInfoVo, sRuleCollInfo);
			num = sRuleCollInfoDao.insertSRuleCollInfo(sRuleCollInfo);
			// 处理特批审批大纲数据 将其保存在biz_rule_adapter表中
			if (inSRuleCollInfoVo.getRuleCollType() != null
					&& inSRuleCollInfoVo.getRuleCollType().equals(RULE_COLL_TYPE.SpecialApproval.getCode())) {
				dealWithAdapter(inSRuleCollInfoVo);
			}
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
            throw e;
		}
		logger.debug("当前新增数据条数为:"+ num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(SRuleCollInfoVO inSRuleCollInfoVo) {
		logger.debug("当前删除数据条件为:"+ inSRuleCollInfoVo);
		int num = 0;
		try {
			SRuleCollInfo sRuleCollInfo = new SRuleCollInfo();
			beanCopy(inSRuleCollInfoVo, sRuleCollInfo);
			num = sRuleCollInfoDao.deleteByPk(sRuleCollInfo);
			// 级联删除规则明细 规则明细参数配置
            if (num == 1) {
                int paramNum = sRuleCollParamDao.deleteByCollId(inSRuleCollInfoVo.getRuleCollId());
                logger.info("删除规则集{}参数明细条数： {}", inSRuleCollInfoVo.getRuleCollId(), paramNum);
                int detailNum = sRuleCollDetailDao.deleteByCollId(inSRuleCollInfoVo.getRuleCollId());
                logger.info("删除规则集{}规则明细条数： {}", inSRuleCollInfoVo.getRuleCollId(), detailNum);
                // 删除适配机构
				BizRuleAdapter adapter = new BizRuleAdapter();
				adapter.setRuleTargetId(inSRuleCollInfoVo.getRuleCollId());
				adapter.setRuleTargetType(inSRuleCollInfoVo.getRuleCollType());
                int adapterNum = bizRuleAdapterDao.deleteByRuleTarget(adapter);
				logger.info("删除规则集{}适配规则条数： {}", inSRuleCollInfoVo.getRuleCollId(), adapterNum);
            }
        } catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
			throw e;
		}
		logger.debug("根据条件:"+ inSRuleCollInfoVo +"删除的数据条数为"+ num);
		return num;
	}


	/**
	 * 更新操作
	 */
	public int updateByPk(SRuleCollInfoVO inSRuleCollInfoVo) {
		logger.debug("当前修改数据为:"+ inSRuleCollInfoVo.toString());
		int num = 0;
		try {
			SRuleCollInfo sRuleCollInfo = new SRuleCollInfo();
			beanCopy(inSRuleCollInfoVo, sRuleCollInfo);
			num = sRuleCollInfoDao.updateByPk(sRuleCollInfo);
			// 处理特批审批大纲数据 将其保存在biz_rule_adapter表中
			if (num == 1
					&& inSRuleCollInfoVo.getRuleCollType() != null
					&& inSRuleCollInfoVo.getRuleCollType().equals(RULE_COLL_TYPE.SpecialApproval.getCode())) {
				dealWithAdapterForUpdate(inSRuleCollInfoVo);
			}
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
            throw e;
		}
		logger.debug("根据条件:"+ inSRuleCollInfoVo +"修改的数据条数为"+ num);
		return num;
	}
	
	/**
	 * 查询操作
	 */
	public SRuleCollInfoVO queryByPk(SRuleCollInfoVO inSRuleCollInfoVo) {
		
		logger.debug("当前查询参数信息为:"+ inSRuleCollInfoVo);
		try {
			SRuleCollInfo querySRuleCollInfo = new SRuleCollInfo();
			beanCopy(inSRuleCollInfoVo, querySRuleCollInfo);
			SRuleCollInfo queryRslSRuleCollInfo = sRuleCollInfoDao.queryByPk(querySRuleCollInfo);
			if (Objects.nonNull(queryRslSRuleCollInfo)) {
				SRuleCollInfoVO outSRuleCollInfoVo = beanCopy(queryRslSRuleCollInfo, new SRuleCollInfoVO());
				logger.debug("当前查询结果为:"+ outSRuleCollInfoVo.toString());
				if (outSRuleCollInfoVo.getRuleCollType() != null
						&& outSRuleCollInfoVo.getRuleCollType().equals(RULE_COLL_TYPE.SpecialApproval.getCode())) {
					loadAdapter(outSRuleCollInfoVo);
				}
				return outSRuleCollInfoVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}

    /**
     * 复制指定的规则集
     * @param srcCollInfo
     * @return
     */
    @Override
    public SRuleCollInfo copyRuleCollInfo(SRuleCollInfoVO srcCollInfoVO, UserInfo userInfo) {
        SRuleCollInfo srcInfo = new SRuleCollInfo();
        SRuleCollInfo targetCollInfo = new SRuleCollInfo();
        srcInfo.setRuleCollId(srcCollInfoVO.getRuleCollId());
        srcInfo = sRuleCollInfoDao.queryByPk(srcInfo);
        // 检查源规则集有效性
        if (srcInfo == null) {
            throw new FireRuleException(FireRuleErrorEnum.E_RULE_COLL_INVALID.getCode(),
                    FireRuleErrorEnum.E_RULE_COLL_INVALID.getMessage(srcCollInfoVO.getRuleCollId()));
        }
        beanCopy(srcInfo, targetCollInfo);
        targetCollInfo.setRuleCollId(BizUtil.getUUID("COLL"));
        if (targetCollInfo.getRuleCollType() != null && targetCollInfo.getRuleCollType().equals(RULE_COLL_TYPE.Approval.getCode())) {
            // 如果复制的是审批大纲，将其状态设置为停用
            targetCollInfo.setRuleCollState(RULE_COLL_STATE.INVALID.getCode());
        }
        targetCollInfo.setCreateTime(BizUtil.getCurrentTime());
        targetCollInfo.setCreateUser(userInfo.getUserId());
        targetCollInfo.setUpdateTime(BizUtil.getCurrentTime());
        targetCollInfo.setUpdateUser(userInfo.getUserId());
        // 保存插库复制的规则集信息
        sRuleCollInfoDao.insertSRuleCollInfo(targetCollInfo);
        // 查询规则集的明细
        copySRuleCollDetail(srcInfo, targetCollInfo);
        return targetCollInfo;
    }

    /**
     * 复制规则集明细规则
     * @param srcCollInfo
     * @param targetCollInfo
     * @return 有明细返回true 无明细返回false 方便判断是否查询明细参数
     */
    private void copySRuleCollDetail(SRuleCollInfo srcCollInfo, SRuleCollInfo targetCollInfo) {
        SRuleCollDetailVO detailVO = new SRuleCollDetailVO();
        detailVO.setRuleCollId(srcCollInfo.getRuleCollId());
        detailVO.setSize(100);
        detailVO.setPage(1);
        List<SRuleCollDetail> detailList = sRuleCollDetailDao.queryAllOwnerByPage(detailVO);
        if (CollectionUtils.isNotEmpty(detailList)) {
            int total = detailVO.getTotal();
            int loop = total / 100;
            if (total % 100 != 0) {
                loop += 1;
            }
            for (int i = 1; i <= loop; i++) {
                if (i > 1) {
                    detailVO.setPage(i);
                    detailList = sRuleCollDetailDao.queryAllOwnerByPage(detailVO);
                }
                for (SRuleCollDetail detail : detailList) {
                    SRuleCollDetail targetDetail = new SRuleCollDetail();
                    beanCopy(detail, targetDetail);
                    targetDetail.setDtlId(BizUtil.getUUID("DTL"));
                    targetDetail.setRuleCollId(targetCollInfo.getRuleCollId());
                    targetDetail.setCreateTime(targetCollInfo.getCreateTime());
                    targetDetail.setCreateUser(targetCollInfo.getCreateUser());
                    targetDetail.setUpdateTime(targetCollInfo.getCreateTime());
                    targetDetail.setUpdateUser(targetCollInfo.getCreateUser());
                    sRuleCollDetailDao.insertSRuleCollDetail(targetDetail);
                    // 复制规则明细参数
                    copySRuleCollParam(srcCollInfo, targetCollInfo, detail, targetDetail);
                }
            }
        }
    }

    /**
     * 复制规则集明细参数配置
     * @param srcCollInfo  源规则集
     * @param targetCollInfo 目标规则集
     * @param srcDetail 源规则集明细规则
     * @param targetDetail 目标规则集明细规则
     */
    private void copySRuleCollParam(SRuleCollInfo srcCollInfo, SRuleCollInfo targetCollInfo, SRuleCollDetail srcDetail, SRuleCollDetail targetDetail) {
        SRuleCollParamVO paramVO = new SRuleCollParamVO();
        paramVO.setDtlId(srcDetail.getDtlId());
        paramVO.setRuleId(srcDetail.getRuleId());
        paramVO.setSize(100);
        paramVO.setPage(1);
        List<SRuleCollParam> paramList = sRuleCollParamDao.queryAllOwnerByPage(paramVO);
        if (CollectionUtils.isNotEmpty(paramList)) {
            int total = paramVO.getTotal();
            int loop = total / 100;
            if (total % 100 != 0) {
                loop += 1;
            }
            for (int i = 1; i <= loop; i++) {
                if (i > 1) {
                    paramVO.setPage(i);
                    paramList = sRuleCollParamDao.queryAllOwnerByPage(paramVO);
                }
                for (SRuleCollParam param : paramList) {
                    param.setDtlId(targetDetail.getDtlId());
                    param.setCreateTime(targetCollInfo.getCreateTime());
                    param.setCreateUser(targetCollInfo.getCreateUser());
                    param.setUpdateTime(targetCollInfo.getCreateTime());
                    param.setUpdateUser(targetCollInfo.getCreateUser());
                    sRuleCollParamDao.insertSRuleCollParam(param);
                }
            }
        }
    }

    /**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<SRuleCollInfoVO> queryAllOwner(SRuleCollInfoVO sRuleCollInfoVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<SRuleCollInfoVO> list = null;
		try {
			List<SRuleCollInfo> sRuleCollInfos = sRuleCollInfoDao.queryAllOwnerByPage(sRuleCollInfoVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:"+ sRuleCollInfos.size());
			pageSet(sRuleCollInfos, sRuleCollInfoVo);
			list = (List<SRuleCollInfoVO>) beansCopy(sRuleCollInfos, SRuleCollInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<SRuleCollInfoVO> queryAllCurrOrg(SRuleCollInfoVO sRuleCollInfoVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<SRuleCollInfo> sRuleCollInfos = sRuleCollInfoDao.queryAllCurrOrgByPage(sRuleCollInfoVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:"+sRuleCollInfos.size());
		List<SRuleCollInfoVO> list = null;
		try {
			pageSet(sRuleCollInfos, sRuleCollInfoVo);
			list = (List<SRuleCollInfoVO>) beansCopy(sRuleCollInfos, SRuleCollInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<SRuleCollInfoVO> queryAllCurrDownOrg(SRuleCollInfoVO sRuleCollInfoVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<SRuleCollInfo> sRuleCollInfos = sRuleCollInfoDao.queryAllCurrDownOrgByPage(sRuleCollInfoVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:"+ sRuleCollInfos.size());
		List<SRuleCollInfoVO> list = null;
		try {
			pageSet(sRuleCollInfos, sRuleCollInfoVo);
			list = (List<SRuleCollInfoVO>) beansCopy(sRuleCollInfos, SRuleCollInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}

	/**
	 * 处理特批审批大纲适配数据更新 先删除匹配的适配数据
	 * @param inSRuleCollInfoVo
	 */
	private void dealWithAdapterForUpdate(SRuleCollInfoVO inSRuleCollInfoVo) {
		// 先删除原有的
		BizRuleAdapter adapter = new BizRuleAdapter();
		adapter.setRuleTargetId(inSRuleCollInfoVo.getRuleCollId());
		adapter.setRuleTargetType(inSRuleCollInfoVo.getRuleCollType());
		adapter.setAdapterCustomDim2(YES_OR_NO.YES.getCode()); // 标注一下是配特批的数据
		int adapterNum = bizRuleAdapterDao.deleteByRuleTarget(adapter);
		logger.info("删除特批审批大纲规则集{}适配规则条数： {}", inSRuleCollInfoVo.getRuleCollId(), adapterNum);
		dealWithAdapter(inSRuleCollInfoVo);
	}
	/**
	 * 更新处理特批的审批大纲的适配数据 将其保存在biz_rule_adapter表中
	 * @param inSRuleCollInfoVo
	 */
	private void dealWithAdapter(SRuleCollInfoVO inSRuleCollInfoVo) {
		String adapterCustomSelect = inSRuleCollInfoVo.getAdapterCustomDim1Select(); // 是否指定城市
		List<String> cityList = inSRuleCollInfoVo.getAdapterCustomDim1(); // 城市代码 多选
		String adapterOrgSelect = inSRuleCollInfoVo.getAdapterOrgNoSelect(); //是否指定机构
		List<String> orgList = inSRuleCollInfoVo.getAdapterOrgNo(); // 机构 多选
		if (adapterCustomSelect == null || adapterOrgSelect == null) {
			throw new RuntimeException("适用抵押物选择或者适用机构选择不能为空");
		}

		if (cityList == null || cityList.isEmpty()) {
			cityList = new ArrayList<>();
			cityList.add(null);
		}
		if (orgList == null || orgList.isEmpty()) {
			orgList = new ArrayList<>();
			orgList.add(null);
		}

		for (String city : cityList) {
			for (String org : orgList) {
				BizRuleAdapter adapter = new BizRuleAdapter();
				adapter.setRecordKeyid(BizUtil.getUUID("ADAP"));
				adapter.setAdapterOrgNo(org);
				adapter.setAdapterCustomDim1(city);
				adapter.setAdapterCustomDim2(YES_OR_NO.YES.getCode());
				adapter.setRuleTargetId(inSRuleCollInfoVo.getRuleCollId());
				adapter.setRuleTargetType(inSRuleCollInfoVo.getRuleCollType());
				adapter.setRuleTargetName(inSRuleCollInfoVo.getRuleCollDesc());

				adapter.setCreateTime(inSRuleCollInfoVo.getCreateTime());
				adapter.setCreateUser(inSRuleCollInfoVo.getCreateUser());
				adapter.setUpdateTime(inSRuleCollInfoVo.getCreateTime());
				adapter.setUpdateUser(inSRuleCollInfoVo.getCreateUser());
				bizRuleAdapterDao.insertBizRuleAdapter(adapter);
			}
		}
	}

	/**
	 * 加载特批审批大纲的适配数据
	 * @param infoVO
	 */
	private void loadAdapter(SRuleCollInfoVO infoVO) {

		BizRuleAdapterVO adapter = new BizRuleAdapterVO();
		adapter.setRuleTargetId(infoVO.getRuleCollId());
		adapter.setRuleTargetType(infoVO.getRuleCollType());
		adapter.setAdapterCustomDim2(YES_OR_NO.YES.getCode()); // 标注一下是配特批的数据
		List<BizRuleAdapter> adapterList = bizRuleAdapterDao.queryAll(adapter);
		if (CollectionUtils.isNotEmpty(adapterList)) {
			Set<String> citySet = new LinkedHashSet<>(adapterList.size());
			Set<String> orgSet = new LinkedHashSet<>(adapterList.size());
			for (BizRuleAdapter el : adapterList) {
				if (el.getAdapterCustomDim1() != null) {
					citySet.add(el.getAdapterCustomDim1());
				}
				if (el.getAdapterOrgNo() != null) {
					orgSet.add(el.getAdapterOrgNo());
				}
			}
			infoVO.setAdapterCustomDim1(new ArrayList<>(citySet));
			infoVO.setAdapterCustomDim1Select(citySet.isEmpty() ? YES_OR_NO.NO.getCode() : YES_OR_NO.YES.getCode());
			infoVO.setAdapterOrgNo(new ArrayList<>(orgSet));
			infoVO.setAdapterOrgNoSelect(orgSet.isEmpty() ? YES_OR_NO.NO.getCode() : YES_OR_NO.YES.getCode());
		}
	}
}
